/*
 * ComponentManager - manage pieces of code that loop with each frame
 *
 * Copyright 2007 James W. Hofmann
 *
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#if flash9
	import flash.events.TimerEvent;
	import flash3f.InputHandler;
	import flash.Lib;
#else neko
	import neko3f.InputHandler;
#end

class ComponentManager
{

	public static var registered : Array<Dynamic> = new Array();
	public static var restart : Bool = false;
	
	#if flash9
	public static function up(evt : TimerEvent)
	#else neko
	public static function up()	
	#end
	{
		
		for (n in registered)
		{
			n.up();
		}
		
		InputHandler.clear();

		if (restart) do_restart();
		
	}

	public static function add(component : Dynamic)
	{
		component.start();
		registered.push(component);
	}
	
	public static function remove(component: Dynamic)
	{
		for (n in registered)
		{
			if (n == component)
			{
				n.end();
				registered.remove(n);		
			}
		}
	}

	public static function removerough(component: Dynamic)
	// remove a component without calling its end function.
	// this kills components that pass off their loops.
	{
		for (n in registered)
		{
			if (n == component)
			{
				registered.remove(n);		
			}
		}
	}

	public static function do_restart()
	{
		#if flash9
		remove(IsoManager);		
		remove(PopTart);
		#end
		
		
		var mark : Array<Dynamic> = new Array();
		
		for (n in registered)
		{
			#if flash9
			if (n!=SFX)
			#end
			mark.push(n);
			
		}
		for (n in mark)
			removerough(n);
		
		#if flash9
		for (n in 0...Lib.current.numChildren)
		{
			Lib.current.removeChildAt(0);
		}
		#end
		
		restart = false;
		
		#if flash9
		ComponentManager.add(Title);	
		#end
	}
	
}
